import * as process from 'process'
import { devHost, prodHost, contentType, tokenName, successCode, statusName } from '@/config'
import { getToken } from '@/utils/token'

let HostUrl: string = ''
if (process.env.NODE_ENV === 'development') {
  // 开发环境下的配置
  HostUrl = devHost
} else {
  // 生产环境下的配置
  HostUrl = prodHost
}

const headers = {
  'content-type': contentType,
  [tokenName]: getToken(),
}
const request = (conf: UniNamespace.RequestOptions): any => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...conf,
      url: HostUrl + conf.url,
      header: {
        ...headers,
        ...conf.header,
      },
      success: (res: UniNamespace.RequestSuccessCallbackResult) => {
        console.log('request:', res)
        if (res.statusCode === 401) {
          uni.redirectTo({
            url: '/pages/login/index',
          })
          return
        }
        resolve(res.data)
      },
      fail: (err: UniNamespace.GeneralCallbackResult) => {
        reject(err)
      },
    })
  })
}

export default request
